using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace LundStocholm.Web.UI.Controls
{
    public enum FeedType
    {
        RSS = 0,
        Atom
    }

    public enum FeedSize
    {
        All = 0,
        Top10 = 10,
        Top25 = 25,
        Top50 = 50
    }

    public enum FeedSource
    {
        Blog = 0,
        Comments = 1
    }

    [DefaultProperty("Title")]
    [ToolboxData("<{0}:RSSFeed runat=server></{0}:RSSFeed>")]
    public class RSSFeed : WebControl
    {
        private DataTable m_dataSource = new DataTable();
        private FeedSize m_size = FeedSize.All;
        private FeedType m_type = FeedType.RSS;
        private FeedSource m_source = FeedSource.Blog;
        private bool m_geoRSS = false;

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public FeedType Feed
        {
            set
            {
                m_type = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public FeedSource RSSType
        {
            get
            {
                return m_source;
            }
            set
            {
                m_source = value;
            }
        }

        public bool EnableGeoRSS
        {
            set { m_geoRSS = value; }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            RenderContents(writer);
            //base.Render(writer);
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public FeedSize LineCount
        {
            set
            {
                m_size = value;
            }
        }

        private string m_title = string.Empty;
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("Defalt RSS Title")]
        [Localizable(true)]
        public string Title
        {
            get
            {
                return m_title;
            }
            set
            {
                m_title = value;
            }
        }

        private string m_description = string.Empty;
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("Default RSS Description")]
        [Localizable(true)]
        public string Description
        {
            get
            {
                return m_description;
            }
            set
            {
                m_description = value;
            }
        }

        private string m_link = string.Empty;
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("http://www.dev.null")]
        [Localizable(true)]
        public string Link
        {
            get
            {
                return m_link;
            }
            set
            {
                m_link = value;
            }
        }


        public DataTable RSSSource
        {
            get
            {
                return m_dataSource;
            }
            set
            {
                m_dataSource = value;
            }
        }

        public LundStocholm.Web.UI.Controls.FeedSource GetFeedSource(object o)
        {
            try
            {
                return (LundStocholm.Web.UI.Controls.FeedSource)Enum.Parse(typeof(LundStocholm.Web.UI.Controls.FeedSource), o.ToString(), true);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("FeedSource kunne ikke genkendes", ex);
            }
        }

        public LundStocholm.Web.UI.Controls.FeedSize GetFeedSize(object o)
        {
            try
            {
                return (LundStocholm.Web.UI.Controls.FeedSize)Enum.Parse(typeof(LundStocholm.Web.UI.Controls.FeedSize), o.ToString(), true);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("FeedSize kunne ikke genkendes", ex);
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            HttpContext.Current.Response.ContentType = "text/xml";
            CultureInfo cInfo = new CultureInfo("en-US");

            //output.Write(Text);
            // Get data from configurationfile
            string RSSTitle = Title;
            string RSSLink = Link;
            string RSSDescription = Description;

            XmlDocument xmlDoc = new XmlDocument();

            string xmlData = "<rss xmlns:georss='http://www.georss.org/georss' xmlns:gml='http://www.opengis.net/gml' xmlns:slash='http://purl.org/rss/1.0/modules/slash/' xmlns:wfw='http://wellformedweb.org/CommentAPI/' version='2.0'></rss>";

            xmlDoc.Load(new StringReader(xmlData));

            XmlElement channel = xmlDoc.CreateElement("channel");
            xmlDoc.DocumentElement.AppendChild(channel);

            XmlElement elem = xmlDoc.CreateElement("title");
            elem.InnerText = RSSTitle;
            channel.AppendChild(elem);
            //xmlDoc.DocumentElement.AppendChild(elem);

            elem = xmlDoc.CreateElement("link");
            elem.InnerText = RSSLink;
            channel.AppendChild(elem);

            elem = xmlDoc.CreateElement("language");
            elem.InnerText = "da-DK";
            xmlDoc.DocumentElement.AppendChild(elem);

            if (m_dataSource.Rows.Count > 0)
            {
                DateTime publicationDate = Convert.ToDateTime(m_dataSource.Rows[0]["CreateDate"]);
                elem = xmlDoc.CreateElement("pubDate");

                elem.InnerText = publicationDate.ToString("ddd, dd MMM yyyy HH:m:ss", cInfo) + " GMT";
                channel.AppendChild(elem);
            }

            elem = xmlDoc.CreateElement("decription");
            elem.InnerText = RSSDescription;
            channel.AppendChild(elem);
            XmlElement item;

            int rowMax = 0;
            if (m_size == FeedSize.All)
            {
                rowMax = m_dataSource.Rows.Count;
            }
            else
            {
                rowMax = (int)m_size;
            }

            for (int rowCount = 0; rowCount < rowMax; rowCount++)
            {
                DataRow row = m_dataSource.Rows[rowCount];
                elem = xmlDoc.CreateElement("item");

                // only add these extra elements if RSS is not CommentRSS
                if (m_source == FeedSource.Blog)
                {

                    XmlElement georss = xmlDoc.CreateElement("georss", "where", "http://www.georss.org/georss");

                    XmlElement gmlPoint = xmlDoc.CreateElement("gml", "Point", "http://www.opengis.net/gml");

                    XmlElement gmlPos = xmlDoc.CreateElement("gml", "pos", "http://www.opengis.net/gml");
                    gmlPos.InnerText = row["GeoLocation"].ToString();

                    gmlPoint.AppendChild(gmlPos);

                    georss.AppendChild(gmlPoint);

                    elem.AppendChild(georss);

                    XmlElement commentCount = xmlDoc.CreateElement("slash", "comments", "http://purl.org/rss/1.0/modules/slash/");
                    commentCount.InnerText = row["CountOfComments"].ToString();
                    elem.AppendChild(commentCount);

                    XmlElement commentURI = xmlDoc.CreateElement("wfw", "commentRss", "http://wellformedweb.org/CommentAPI/");
                    commentURI.InnerText = this.Link + "/rss/comments.aspx?id=" + row["MessageID"].ToString();
                    elem.AppendChild(commentURI);
                }

                item = xmlDoc.CreateElement("title");
                item.InnerText = row["Subject"].ToString();
                elem.AppendChild(item);

                item = xmlDoc.CreateElement("link");
                item.InnerText = row["BlogPostURI"].ToString();
                elem.AppendChild(item);



                item = xmlDoc.CreateElement("description");
                XmlCDataSection cdata = xmlDoc.CreateCDataSection(row["body"].ToString());
                item.AppendChild(cdata);
                elem.AppendChild(item);

                item = xmlDoc.CreateElement("author");
                item.InnerText = row["AuthorName"].ToString();
                elem.AppendChild(item);

                item = xmlDoc.CreateElement("pubDate");
                DateTime publicationDate = Convert.ToDateTime(row["CreateDate"]);
                item.InnerText = publicationDate.ToString("ddd, dd MMM yyyy HH:m:ss", cInfo) + " GMT";
                //item.InnerText = Convert.ToDateTime(row["CreateDate"]).ToString("dd, ddd MMM yyyy HH:m:ss") + " GMT";
                elem.AppendChild(item);

                channel.AppendChild(elem);
            }

            //Create an XML declaration. 
            XmlDeclaration xmldecl;
            xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");

            //Add the new node to the document.
            XmlElement root2 = xmlDoc.DocumentElement;
            xmlDoc.InsertBefore(xmldecl, root2);
            output.Write(xmlDoc.OuterXml);
        }
    }
}
